package com.zz.array;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class L1Solution {
    public int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] retu = new int[2];
        //第一步把所有的数转入map，key为数组元素，value为对应下标
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        //第二步 target-数组中每个数，判断剩下的数在不在map中
        for (int i = 0; i < nums.length; i++) {
            int j = target - nums[i];
            if(map.containsKey(j) && i != map.get(j)){
                retu[0] = i;
                retu[1] = map.get(j);
            }
        }
        return retu;
    }

    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }

    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }
}
